import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams, ToastController, ViewController} from 'ionic-angular';
import {Api} from "../../providers/api/api";
import {TranslateService} from "@ngx-translate/core";

/**
 * Generated class for the SearchPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-search',
  templateUrl: 'search.html',
})
export class SearchPage {
  pages: Array<any> = [];
  private networkErrorString: string;

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public api: Api,
              public translateService: TranslateService,
              public toastCtrl: ToastController,
              public viewController: ViewController) {
    this.translateService.get('NETWORK_ERROR').subscribe((value) => {
      this.networkErrorString = value;
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad SearchPage');
  }

  search(ev: any) {
    let val = ev.target.value;
    if (val && val.trim() !== '') {
      let seq = this.api.get('plans/search?planName=' + val).share();
      seq.subscribe((res: any) => {
        // If the API returned a successful response, mark the user as logged in
        if (res) {
          this.pages = [];
          this.pages = this.pages.concat(res);
        } else {
          this.showToast().present();
        }
      }, err => {
        this.showToast().present();
        console.error('ERROR', err);
      });
    }
  }

  dismiss() {
    this.viewController.dismiss();
  }

  showToast() {
    return this.toastCtrl.create({
      message: this.networkErrorString,
      duration: 1000,
      position: 'top'
    });
  }

  openDetail(planDetail) {
    this.navCtrl.push('PlanDetailPage', planDetail);
  }
}
